<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="CPaymentRecordForm">
          <a-row>
            <a-col :span="12">
              <a-form-item label="收款标题" v-bind="validateInfos.paymentTitle" id="CPaymentRecordForm-paymentTitle" name="paymentTitle">
                <a-input v-model:value="formData.paymentTitle" placeholder="请输入收款标题" style="width: 100%" />
              </a-form-item>
            </a-col>
						<a-col :span="12">
							<a-form-item label="项目" v-bind="validateInfos.projectId" id="CPaymentRecordForm-projectId" name="projectId">
								 <j-dict-select-tag showSearch="true"   v-model:value="formData.projectId" dictCode="c_project_application,project_name,id" placeholder="请选择项目"  allow-clear />
							</a-form-item>
						</a-col>
            <a-col :span="12">
              <a-form-item label="收款总包主体" v-bind="validateInfos.companyId" id="CPaymentRequestForm-companyId" name="companyId">
                 <j-dict-select-tag showSearch="true"
                  v-model:value="formData.companyId"
                  dictCode="c_company_info,company_name,id"
                  placeholder="请选择总包主体"
                  allow-clear
                />
              </a-form-item>
            </a-col>

						<a-col :span="12">
							<a-form-item label="收款日期" v-bind="validateInfos.paymentDate" id="CPaymentRecordForm-paymentDate" name="paymentDate">
								<a-date-picker placeholder="请选择收款日期"  v-model:value="formData.paymentDate" showTime value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="收款金额" v-bind="validateInfos.paymentAmount" id="CPaymentRecordForm-paymentAmount" name="paymentAmount">
								<a-input-number v-model:value="formData.paymentAmount" placeholder="请输入收款金额" style="width: 100%" />
							</a-form-item>
						</a-col>

						<a-col :span="12">
							<a-form-item label="收款方式" v-bind="validateInfos.paymentMethod" id="CPaymentRecordForm-paymentMethod" name="paymentMethod">
								 <j-dict-select-tag showSearch="true"   v-model:value="formData.paymentMethod" dictCode="payment_methods" placeholder="请选择收款方式"  allow-clear />
							</a-form-item>
						</a-col>

            <a-col :span="12">
              <a-form-item label="收款备注" v-bind="validateInfos.paymentRemark" id="CPaymentInvoiceForm-paymentRemark" name="paymentRemark">
                <a-textarea v-model:value="formData.paymentRemark" :rows="4" placeholder="请输入收款备注" />
              </a-form-item>
            </a-col>


            <a-divider >收款银行信息</a-divider >
						<a-col :span="12">
							<a-form-item label="银行名称" v-bind="validateInfos.bankName" id="CPaymentRecordForm-bankName" name="bankName">
								 <j-dict-select-tag showSearch="true"   v-model:value="formData.bankName" dictCode="bank_name" placeholder="请选择银行名称"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="支行信息" v-bind="validateInfos.bankBranch" id="CPaymentRecordForm-bankBranch" name="bankBranch">
								<a-input v-model:value="formData.bankBranch" placeholder="请输入支行信息"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="银行账号" v-bind="validateInfos.accountNumber" id="CPaymentRecordForm-accountNumber" name="accountNumber">
								<a-input v-model:value="formData.accountNumber" placeholder="请输入银行账号"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="开户人名称" v-bind="validateInfos.accountHolderName" id="CPaymentRecordForm-accountHolderName" name="accountHolderName">
								<a-input v-model:value="formData.accountHolderName" placeholder="请输入开户人名称"  allow-clear ></a-input>
							</a-form-item>

						</a-col>
            <a-col :span="12">
              <a-form-item label="收款凭证" v-bind="validateInfos.recordFile" id="CPaymentRecordForm-recordFile" name="recordFile">
                <j-upload v-model:value="formData.recordFile"  dragger="true"   :show-upload-list="{ showDownloadIcon: true, showRemoveIcon: true }" ></j-upload>
              </a-form-item>
            </a-col>
          <!-----开票登记------>
            <a-col :span="24">
              <a-divider>关联开票登记</a-divider>
            </a-col>
            <a-col :span="24">
              <a-form-item label="开票登记" v-bind="validateInfos.invoiceApplyId" id="CProjectApplicationForm-invoiceApplyId" name="invoiceApplyId">
                <a-select
                  v-model:value="formData.invoiceApplyId"
                  mode="multiple"
                  style="width: 100%"
                  placeholder="请选择发票"
                  :options="invoiceApplySplitList"
                  @change="handleChange"
                ></a-select>
              </a-form-item>
            </a-col>


            <a-col :span="24">
              <!-- 拆分发票-->
              <a-table :columns="pequestColumns" :data-source="invoiceApplyList" :pagination="false" bordered>
                <template #bodyCell="{ column, text, record }">
                  <template v-if="['splitAmount'].includes(column.dataIndex)"
                  ><!-- 设置编辑的字段-->
                    <div>
                      <a-input v-if="editableData[record.id]" v-model:value="editableData[record.id][column.dataIndex]" style="margin: -5px 0" />
                      <template v-else>
                        {{ text }}
                      </template>
                    </div>
                  </template>

                  <template v-else-if="column.dataIndex === 'operation'">
                    <div class="editable-row-operations">
                      <span v-if="editableData[record.id]">
                        <a-typography-link @click="save(record.id)"> <a style="margin-right: 10px">保存</a></a-typography-link>
                        <a-popconfirm title="是否取消？" @confirm="cancel(record.id)">
                          <a>取消</a>
                        </a-popconfirm>
                      </span>
                      <span v-else>
                        <a @click="editPequest(record.id)">编辑</a>
                      </span>
                    </div>
                  </template>
                </template>

                <template #summary>
                  <a-table-summary fixed>
                    <a-table-summary-row>
                      <a-table-summary-cell :index="0">合计</a-table-summary-cell>
                      <a-table-summary-cell :index="1"></a-table-summary-cell>
                      <a-table-summary-cell :index="1"></a-table-summary-cell>
                      <a-table-summary-cell :index="1"></a-table-summary-cell>
                      <a-table-summary-cell :index="1"></a-table-summary-cell>
                      <a-table-summary-cell :index="1">{{ sumAmount }}</a-table-summary-cell>
                      <a-table-summary-cell :index="1"></a-table-summary-cell>
                    </a-table-summary-row>
                  </a-table-summary>
                </template>
              </a-table>
            </a-col>


          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted, type UnwrapRef } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import { getValueType } from '/@/utils';
  import { getLoadinvoiceAppleSplit, saveOrUpdate } from '../CPaymentRecord.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { pequestColumns } from '@/views/paymentrequest/components/CPequest.data';
  import { getLoadinvoiceSplit } from '@/views/paymentrequest/CPaymentRequest.api';
  import { cloneDeep } from 'lodash-es';
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const editableData: UnwrapRef<Record<string, DataItem>> = reactive({});
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    paymentStatus: '',   
    projectId: '',   
    paymentDate: '',   
    paymentAmount: undefined,
    recordFile: '',   
    paymentMethod: '转账',
    bankName: '',   
    bankBranch: '',   
    accountNumber: '',   
    accountHolderName: '',
    companyId:'',
    paymentTitle:'',
    invoiceApplyId: [],
    paymentRemark:'',
  });
interface DataItem {
  id: string;
  title: string;
  invoiceNumber: string;
  splitAmount: Number;
  totalAmountWithTax: Number;
  highestSplitAmount: Number;
}
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  const invoiceApplySplitList = ref();
  const invoiceApplyMap = ref();
  const sumAmount = ref(0);
  const invoiceApplyList = ref();
  //表单验证
  const validatorRules = reactive({
    paymentDate: [{ required: true, message: '请输入收款日期!'},],
    paymentAmount: [{ required: true, message: '请输入收款金额!'},],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  
  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  async function edit(record) {
    invoiceApplyList.value = [];
    sumAmount.value = 0;
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if (key === 'invoiceApplyId' && record[key]) {
          tmpData[key] = record[key].split(',');
        } else if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });

    const param = {
      projectId: record.projectId,
      invoiceAppleId: record.id

    };
    await loadinvoiceAppleSplit(param);
    if (record.id) {
      handleData(record['invoiceApplyId'].split(','));
     // companyChange(record.companyId)
    }
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    if(Object.keys(editableData).length > 0){
      createMessage.warning('请先保存所有拆分发票');
      return;
    }
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    model['invoiceApplyList'] = invoiceApplyList.value;
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  //加载 下拉选择数据
  async function loadinvoiceAppleSplit(param) {
    invoiceApplySplitList.value = [];
    invoiceApplyMap.value = {};
    const rest = await getLoadinvoiceAppleSplit(param);
    for (var i = 0; i < rest.length; i++) {
      const result = rest[i];
      invoiceApplySplitList.value.push({
        value: result.id,
        label: result.invoiceNumber,
      });
      invoiceApplyMap[result.id] = result;
    }

  }
  function handleChange() {
    handleData(formData.invoiceApplyId);
  }

  function handleData(invoiceApplyIds) {
    sumAmount.value = 0;
    invoiceApplyList.value = [];
    for (var i = 0; i < invoiceApplyIds.length; i++) {
      if(invoiceApplyIds[i] != undefined && invoiceApplyIds[i].length > 0){
        const result2 = invoiceApplyMap[invoiceApplyIds[i]];
        if(result2 != undefined){
          let remaining = result2.totalAmountWithTax-result2.splitAmountNot-result2.splitAmount
          remaining = parseFloat(remaining.toFixed(2));

          invoiceApplyList.value.push({
            id: result2.id,
            title: result2.title,
            invoiceNumber: result2.invoiceNumber,
            totalAmountWithTax: result2.totalAmountWithTax,
            highestSplitAmount: remaining,
            splitAmount: result2.splitAmount,
            splitAmountNot: result2.splitAmountNot,
          });
          //合计
          sumAmount.value += parseFloat(result2.splitAmount);
        }

      }
    }
    sumAmount.value = parseFloat(sumAmount.value.toFixed(2));
  }


  //拆分发票
  function editPequest(key) {
    editableData[key] = cloneDeep(invoiceApplyList.value.filter((item) => key === item.id)[0]);
  }
  //拆分发票
  function cancel(key) {
    delete editableData[key];
  }
  //拆分发票
  const save = (key: string) => {
    const invoiceValue = invoiceApplyList.value.filter((item) => key === item.id)[0];
    const editValue = editableData[key];

    let remaining = invoiceValue.totalAmountWithTax-invoiceValue.splitAmountNot-editValue.splitAmount
    remaining = parseFloat(remaining.toFixed(2));

    if (remaining < 0) {
      createMessage.warning('拆分价格大于最大拆分价');
      return;
    }
    invoiceValue.highestSplitAmount = remaining
    editValue.highestSplitAmount = remaining
    editValue.splitAmount =  parseFloat(editValue.splitAmount).toFixed(2)

    Object.assign(invoiceApplyList.value.filter((item) => key === item.id)[0], editableData[key]);
    delete editableData[key];
    sumAmount.value = 0;
    for (var i = 0; i < invoiceApplyList.value.length; i++) {
      const result = invoiceApplyList.value[i];
      //合计
      sumAmount.value += parseFloat(result.splitAmount);
    }
    sumAmount.value = parseFloat(sumAmount.value.toFixed(2));
  };


  defineExpose({
    add,
    edit,
    submitForm,
    loadinvoiceAppleSplit,
    handleChange,
    handleData,
    invoiceApplyMap,
    editPequest,
    cancel,
    save
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
